#!/bin/bash
# Generate Comprehensive 5GC Analysis Report
# Analyzes both control plane and user plane captures

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CAPTURES_DIR="../docs/5gc-interfaces/captures"
OUTPUT_DIR="./analysis/comprehensive"
REPORT_FILE="$OUTPUT_DIR/5gc_comprehensive_report.txt"

echo "=== 5GC Comprehensive Analysis Report ==="
echo "Script directory: $SCRIPT_DIR"
echo "Captures directory: $CAPTURES_DIR"
echo "Output directory: $OUTPUT_DIR"
echo "Report file: $REPORT_FILE"
echo

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Run control plane analysis
echo "Running control plane analysis..."
if [[ -f "$SCRIPT_DIR/analyze-control-plane.sh" ]]; then
    bash "$SCRIPT_DIR/analyze-control-plane.sh"
else
    echo "⚠ Control plane analysis script not found"
fi

# Run user plane analysis
echo "Running user plane analysis..."
if [[ -f "$SCRIPT_DIR/analyze-user-plane.sh" ]]; then
    bash "$SCRIPT_DIR/analyze-user-plane.sh"
else
    echo "⚠ User plane analysis script not found"
fi

# Generate comprehensive report
echo "=== Generating Comprehensive Report ==="

cat > "$REPORT_FILE" << EOF
5GC Comprehensive Analysis Report
=================================
Generated: $(date)
Script: $0

OVERVIEW
--------
This report provides a comprehensive analysis of 5GC interface captures,
including both control plane and user plane traffic patterns.

TESTBED CONFIGURATION
--------------------
- VM1 (192.168.1.206): AMF, SMF, MongoDB
- VM2 (192.168.1.219): UPF
- VM3 (192.168.1.221): gNodeB (UERANSIM)
- VM4 (192.168.1.224): UE (UERANSIM)

INTERFACE MAPPING
-----------------
Control Plane:
- N2: gNodeB (192.168.1.221) ↔ AMF (192.168.1.206:38412) - SCTP
- N4: SMF (192.168.1.206) ↔ UPF (192.168.1.219:8805) - SCTP
- SBI: 5GC Functions (192.168.1.206:7777/7778) - HTTP/2

User Plane:
- N1: UE ↔ gNodeB - NAS messages
- N3: gNodeB ↔ UPF (192.168.1.219:2152) - GTP-U
- N6: UPF ↔ Internet - NAT traffic

EOF

# Add control plane analysis
if [[ -f "./analysis/control-plane/summary_report.txt" ]]; then
    echo "" >> "$REPORT_FILE"
    echo "CONTROL PLANE ANALYSIS" >> "$REPORT_FILE"
    echo "=====================" >> "$REPORT_FILE"
    cat "./analysis/control-plane/summary_report.txt" >> "$REPORT_FILE"
fi

# Add user plane analysis
if [[ -f "./analysis/user-plane/summary_report.txt" ]]; then
    echo "" >> "$REPORT_FILE"
    echo "USER PLANE ANALYSIS" >> "$REPORT_FILE"
    echo "===================" >> "$REPORT_FILE"
    cat "./analysis/user-plane/summary_report.txt" >> "$REPORT_FILE"
fi

# Add traffic flow analysis
echo "" >> "$REPORT_FILE"
echo "TRAFFIC FLOW ANALYSIS" >> "$REPORT_FILE"
echo "====================" >> "$REPORT_FILE"

# Analyze N2 interface specifically
if [[ -f "./analysis/control-plane/n2_amf_analysis.json" ]]; then
    echo "" >> "$REPORT_FILE"
    echo "N2 Interface (gNodeB ↔ AMF) Analysis:" >> "$REPORT_FILE"
    python3 -c "
import json
try:
    with open('./analysis/control-plane/n2_amf_analysis.json', 'r') as f:
        data = json.load(f)
    
    print(f'Total packets: {data[\"metadata\"][\"total_packets\"]}')
    
    # Count SCTP packets
    sctp_count = data['statistics']['protocols'].get('SCTP', 0)
    print(f'SCTP packets: {sctp_count}')
    
    # Look for specific SCTP messages
    sctp_packets = [p for p in data['packets'] if p['protocol'] == 'SCTP']
    hb_count = len([p for p in sctp_packets if 'HB' in p['details']])
    data_count = len([p for p in sctp_packets if 'DATA' in p['details']])
    
    print(f'Heartbeat messages: {hb_count}')
    print(f'Data messages: {data_count}')
    
    # Check for NGAP messages
    ngap_messages = [p for p in sctp_packets if any(msg in p['details'].upper() for msg in ['NGAP', 'REGISTRATION', 'PDU', 'HANDOVER'])]
    print(f'NGAP-related messages: {len(ngap_messages)}')
    
except Exception as e:
    print(f'Error analyzing N2 interface: {e}')
" >> "$REPORT_FILE"
fi

# Analyze N4 interface specifically
if [[ -f "./analysis/control-plane/n4_smf_analysis.json" ]]; then
    echo "" >> "$REPORT_FILE"
    echo "N4 Interface (SMF ↔ UPF) Analysis:" >> "$REPORT_FILE"
    python3 -c "
import json
try:
    with open('./analysis/control-plane/n4_smf_analysis.json', 'r') as f:
        data = json.load(f)
    
    print(f'Total packets: {data[\"metadata\"][\"total_packets\"]}')
    
    # Count SCTP packets
    sctp_count = data['statistics']['protocols'].get('SCTP', 0)
    print(f'SCTP packets: {sctp_count}')
    
    # Look for PFCP messages
    sctp_packets = [p for p in data['packets'] if p['protocol'] == 'SCTP']
    pfcp_messages = [p for p in sctp_packets if any(msg in p['details'].upper() for msg in ['PFCP', 'SESSION', 'ESTABLISHMENT', 'MODIFICATION'])]
    print(f'PFCP-related messages: {len(pfcp_messages)}')
    
except Exception as e:
    print(f'Error analyzing N4 interface: {e}')
" >> "$REPORT_FILE"
fi

# Analyze user plane traffic
if [[ -f "./analysis/user-plane/n3_user_plane_analysis.json" ]]; then
    echo "" >> "$REPORT_FILE"
    echo "N3 Interface (User Plane) Analysis:" >> "$REPORT_FILE"
    python3 -c "
import json
try:
    with open('./analysis/user-plane/n3_user_plane_analysis.json', 'r') as f:
        data = json.load(f)
    
    print(f'Total packets: {data[\"metadata\"][\"total_packets\"]}')
    
    # Calculate data volume
    total_size = 0
    for packet in data['packets']:
        if packet.get('size'):
            total_size += packet['size']
    
    if total_size > 0:
        print(f'Total data volume: {total_size} bytes ({total_size/1024:.2f} KB)')
    
    # Analyze protocols
    protocols = data['statistics']['protocols']
    for protocol, count in protocols.items():
        print(f'{protocol} packets: {count}')
    
    # Check for GTP-U traffic
    gtpu_packets = [p for p in data['packets'] if 'GTP' in p['details'].upper()]
    print(f'GTP-U packets: {len(gtpu_packets)}')
    
except Exception as e:
    print(f'Error analyzing N3 interface: {e}')
" >> "$REPORT_FILE"
fi

# Add recommendations
echo "" >> "$REPORT_FILE"
echo "RECOMMENDATIONS" >> "$REPORT_FILE"
echo "===============" >> "$REPORT_FILE"

echo "1. Control Plane Health:" >> "$REPORT_FILE"
if [[ -f "./analysis/control-plane/n2_amf_analysis.json" ]]; then
    python3 -c "
import json
try:
    with open('./analysis/control-plane/n2_amf_analysis.json', 'r') as f:
        data = json.load(f)
    
    sctp_count = data['statistics']['protocols'].get('SCTP', 0)
    if sctp_count > 0:
        print('✓ N2 interface is active with SCTP traffic')
    else:
        print('✗ N2 interface shows no SCTP traffic - check gNodeB-AMF connectivity')
        
except Exception as e:
    print('✗ Unable to analyze N2 interface')
" >> "$REPORT_FILE"
else
    echo "✗ N2 interface analysis not available" >> "$REPORT_FILE"
fi

echo "2. User Plane Performance:" >> "$REPORT_FILE"
if [[ -f "./analysis/user-plane/n3_user_plane_analysis.json" ]]; then
    python3 -c "
import json
try:
    with open('./analysis/user-plane/n3_user_plane_analysis.json', 'r') as f:
        data = json.load(f)
    
    total_packets = data['metadata']['total_packets']
    if total_packets > 0:
        print(f'✓ User plane traffic detected: {total_packets} packets')
    else:
        print('✗ No user plane traffic detected - check UE registration and PDU sessions')
        
except Exception as e:
    print('✗ Unable to analyze user plane traffic')
" >> "$REPORT_FILE"
else
    echo "✗ User plane analysis not available" >> "$REPORT_FILE"
fi

echo "3. Network Connectivity:" >> "$REPORT_FILE"
echo "   - Verify all VMs are reachable via ping" >> "$REPORT_FILE"
echo "   - Check firewall rules allow required ports" >> "$REPORT_FILE"
echo "   - Ensure services are running on correct interfaces" >> "$REPORT_FILE"

echo "4. Troubleshooting Steps:" >> "$REPORT_FILE"
echo "   - Run health-check.sh to verify service status" >> "$REPORT_FILE"
echo "   - Check logs: journalctl -u open5gs-*" >> "$REPORT_FILE"
echo "   - Verify UE registration in MongoDB" >> "$REPORT_FILE"
echo "   - Test connectivity between components" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "FILES GENERATED" >> "$REPORT_FILE"
echo "===============" >> "$REPORT_FILE"
echo "- $REPORT_FILE: This comprehensive report" >> "$REPORT_FILE"
echo "- ./analysis/control-plane/: Control plane analysis files" >> "$REPORT_FILE"
echo "- ./analysis/user-plane/: User plane analysis files" >> "$REPORT_FILE"

echo "" >> "$REPORT_FILE"
echo "NEXT STEPS" >> "$REPORT_FILE"
echo "==========" >> "$REPORT_FILE"
echo "1. Review the detailed analysis files" >> "$REPORT_FILE"
echo "2. Check for any error patterns in the traffic" >> "$REPORT_FILE"
echo "3. Verify expected 5G procedures are present" >> "$REPORT_FILE"
echo "4. Use the analysis to optimize network configuration" >> "$REPORT_FILE"

echo
echo "=== Comprehensive Report Generated ==="
echo "Report saved to: $REPORT_FILE"
echo
echo "To view the report:"
echo "  cat $REPORT_FILE"
echo "  less $REPORT_FILE"
echo
echo "To analyze specific interfaces:"
echo "  jq '.' ./analysis/control-plane/*.json"
echo "  jq '.' ./analysis/user-plane/*.json" 